﻿using SolidWorks.Base;
using SolidWorks.Interop.sldworks;
using System;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;

namespace Paine.SolidWorks.Exe
{
    public partial class FrmPropertiesEdit : Form
    {

        //Todo: 用户自己切换模型之后，未做检查处理。



        private readonly ModelDoc2 swModel;

        public FrmPropertiesEdit(ModelDoc2 model)
        {
            InitializeComponent();
            swModel = model;
        }

        private void FrmPropertiesEdit_Load(object sender, EventArgs e)
        {
            if (swModel == null)
            {
                return;
            }


           

            labCurrentModel.Text = System.IO.Path.GetFileName(swModel.GetPathName());

            if (string.IsNullOrWhiteSpace(labCurrentModel.Text))
            {

                labCurrentModel.Text = swModel.GetTitle();
            }


            var allProperties = PropertiesHelper.GetModelProperties(swModel);

            InitDataGridView(dgvCustomProperties);

            foreach (var propertyConfigInfo in allProperties)
            {
                if (string.IsNullOrWhiteSpace(propertyConfigInfo.ConfigName))
                {
                    var tempProItem = propertyConfigInfo.PropertyItems;

                    dgvCustomProperties.Tag = propertyConfigInfo;

                    foreach (var propertyItem in tempProItem)
                    {
                        dgvCustomProperties.Rows.Add(propertyItem.ItemName, PropertiesHelper.GetTypeNameForPropertyType(propertyItem.ItemType),
                            propertyItem.ItemValue);

                        var tempRow = dgvCustomProperties.Rows[dgvCustomProperties.RowCount - 2];

                        tempRow.Tag = propertyItem;
                    }
                }
                else
                {
                    tabProperties.TabPages.Add(propertyConfigInfo.ConfigName, propertyConfigInfo.ConfigName);

                    var tempPage = tabProperties.TabPages[propertyConfigInfo.ConfigName];
                    var tempDGV = new DataGridView();
                    tempDGV.Dock = DockStyle.Fill;
                    InitDataGridView(tempDGV);

                    tempPage.Controls.Add(tempDGV);
                    tempDGV.CellEndEdit += dgvCustomProperties_CellEndEdit;

                    var tempProItem = propertyConfigInfo.PropertyItems;

                    tempDGV.Tag = propertyConfigInfo;

                    foreach (var propertyItem in tempProItem)
                    {
                        tempDGV.Rows.Add(propertyItem.ItemName, PropertiesHelper.GetTypeNameForPropertyType(propertyItem.ItemType),
                            propertyItem.ItemValue);

                        var tempRow = tempDGV.Rows[tempDGV.RowCount - 2];

                        tempRow.Tag = propertyItem;
                    }
                }
            }
        }

        /// <summary>
        /// 初始化表
        /// </summary>
        /// <param name="dataGridView"></param>

        private void InitDataGridView(DataGridView dataGridView)
        {
            dataGridView.Columns.Add("Name", "名称");
            dataGridView.Columns.Add("Type", "类型");
            dataGridView.Columns.Add("Value", "值");
            dataGridView.Columns[0].Width = 200;
            dataGridView.Columns[1].Width = 200;
            dataGridView.Columns[2].Width = 400;

            dataGridView.UserDeletingRow += dgvCustomProperties_UserDeletingRow;
            dataGridView.CellEndEdit += dgvCustomProperties_CellEndEdit;
            dataGridView.CurrentCellChanged += dgvCustomProperties_CurrentCellChanged;
            dataGridView.DefaultValuesNeeded += dgvCustomProperties_DefaultValuesNeeded;

            

        }

      

        private void dgvCustomProperties_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                if (!chkAutoSave.Checked) return;
                if (!(sender is DataGridView dgv)) return;
                var PropertiesInfo = dgv.Tag as PropertyInfo;

                var editRow = dgv.Rows[e.RowIndex];

                var oldPropertyItem = editRow.Tag as PropertyItem;

                var newPropertyItem = new PropertyItem
                {
                    ItemName = editRow.Cells[0].Value?.ToString(),
                    ItemValue = editRow.Cells[2].Value?.ToString(),
                    ItemType = PropertiesHelper.GetCustomInforTypeByName(editRow.Cells[1].Value?.ToString()) // swCustomInfoType_e.swCustomInfoText;
                };


                //检查是否有重复
                if (oldPropertyItem != null && PropertiesInfo != null && PropertiesInfo.PropertyItems.Any(x => x.ItemName == newPropertyItem.ItemName) && oldPropertyItem.ItemName != newPropertyItem.ItemName)
                {

                    MessageBox.Show(@"当前修改的名称已经存在，请重新输入。");
                    editRow.Cells[0].Value = oldPropertyItem.ItemName;
                    return;
                }

                //修改 增加 

                if (oldPropertyItem != null) //修改
                {
                    if (newPropertyItem.ItemName != oldPropertyItem.ItemName || newPropertyItem.ItemType != oldPropertyItem.ItemType)
                    {
                        if (PropertiesInfo != null)
                            PropertiesHelper.DeleteCustomProperty(swModel, PropertiesInfo.ConfigName,
                                oldPropertyItem.ItemName);
                    }
                }
                else
                {
                    if (string.IsNullOrWhiteSpace(newPropertyItem.ItemName))
                    {
                        return;
                    }
                }

                if (PropertiesInfo != null)
                {
                    if (oldPropertyItem != null && newPropertyItem.ItemName != oldPropertyItem.ItemName)
                    {
                        PropertiesHelper.ModifyCustomProperty(swModel, PropertiesInfo.ConfigName, newPropertyItem.ItemName,
                            newPropertyItem.ItemValue, (int)newPropertyItem.ItemType,true);
                    }
                    else
                    {
                        PropertiesHelper.ModifyCustomProperty(swModel, PropertiesInfo.ConfigName, newPropertyItem.ItemName,
                            newPropertyItem.ItemValue, (int)newPropertyItem.ItemType, false);
                    }

                  

                    editRow.Tag = newPropertyItem;

                    PropertiesInfo.PropertyItems.Remove(oldPropertyItem);
                    PropertiesInfo.PropertyItems.Add(newPropertyItem);
                }
            }
            catch (Exception exception)
            {
                MessageBox.Show($@"保存出错，请检查数据合理性。{exception.StackTrace}");
            }
        }

    

        private DataGridView dataGridView1;


        private void dgvCustomProperties_CurrentCellChanged(object sender, EventArgs e)
        {
            try
            {

                dataGridView1 = sender as DataGridView;
                
                if (dataGridView1==null)
                {
                    return;
                }

                dataGridView1.Controls.Remove(comboBox1);

                dataGridView1.Controls.Add(comboBox1);

                if (dataGridView1.CurrentCell?.ColumnIndex == 1)
                {
                    
                    Rectangle rect = dataGridView1.GetCellDisplayRectangle(dataGridView1.CurrentCell.ColumnIndex, dataGridView1.CurrentCell.RowIndex, false);
                    comboBox1.Left =  rect.Left;
                    comboBox1.Top = rect.Top ;
                    comboBox1.Width = rect.Width;
                    comboBox1.Height = rect.Height;
                    comboBox1.SelectedItem = dataGridView1.CurrentCell.Value;
                    comboBox1.Visible = true;
                }
                else
                {
                    comboBox1.Visible = false;
                }
            }
            catch
            {
                // ignored
            }
        }
   
        /// <summary>
        /// 选择完数据，修改值 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void comboBox1_SelectedValueChanged(object sender, EventArgs e)
        {
            if (dataGridView1.CurrentCell != null)
                dataGridView1.CurrentCell.Value = comboBox1.SelectedItem.ToString();
        }

  

        private void dgvCustomProperties_UserDeletingRow(object sender, DataGridViewRowCancelEventArgs e)
        {
            if (chkAutoSave.Checked)
            {
                if (sender is DataGridView dgv)
                {
                    var PropertiesInfo = dgv.Tag as PropertyInfo;

                    var editRow = e.Row;

                    var oldPropertyItem = editRow.Tag as PropertyItem;


                    if (PropertiesInfo == null) return;
                    if (oldPropertyItem == null) return;
                    PropertiesHelper.DeleteCustomProperty(swModel, PropertiesInfo.ConfigName,
                        oldPropertyItem.ItemName);

                    PropertiesInfo.PropertyItems.Remove(oldPropertyItem);
                }
            }
        }

    

        private void dgvCustomProperties_DefaultValuesNeeded(object sender, DataGridViewRowEventArgs e)
        {
            e.Row.Cells[1].Value = "文字";
        }
    }
}